<template>
  <view class="admin-container">
    <!-- 返回按鈕 -->
    <BackButton />
    
    <view class="admin-tabs">
      <button :class="{active: tab==='task'}" @click="tab = 'task'">任务管理</button>
      <button :class="{active: tab==='user'}" @click="() => tab='user'">用户管理</button>
      <button :class="{active: tab==='config'}" @click="() => tab='config'">配置热加载</button>
      <button :class="{active: tab==='database'}" @click="() => tab='database'">数据库管理</button>
    </view>
    <view v-if="tab==='task'">
      <view class="admin-section">
        <view class="admin-search">
          <input v-model="taskQuery.keyword" placeholder="关键词" />
          <input v-model="taskQuery.publisherId" placeholder="发布者ID" type="number" />
          <input v-model="taskQuery.status" placeholder="状态" />
          <button @click="getTasks">搜索</button>
        </view>
        <view>
          <view v-for="task in tasks" :key="task.taskId" class="admin-list-item">
            <text>{{task.title}} (ID:{{task.taskId}}) 状态:{{task.status}}</text>
            <button @click="deleteTask(task.taskId)" type="warn">删除</button>
          </view>
        </view>
        <view class="admin-pagination">
          <button @click="() => taskQuery.page--" :disabled="taskQuery.page===0">上一页</button>
          <text>第{{taskQuery.page+1}}页</text>
          <button @click="() => taskQuery.page++" :disabled="!hasMoreTask">下一页</button>
        </view>
      </view>
    </view>
    <view v-if="tab==='user'">
      <view class="admin-section">
        <view class="admin-search">
          <input v-model="userQuery.keyword" placeholder="昵称/手机号/邮箱" />
          <button @click="getUsers">搜索</button>
        </view>
        <view>
          <view v-for="user in users" :key="user.uid" class="admin-list-item">
            <text>{{user.nickname}} (UID:{{user.uid}}) 状态:{{user.uidStatus}}</text>
            <button @click="() => showUserDetail(user.uid)">详情</button>
			<button v-if="user.uidStatus === 'unbanned'" @click="() => banUser(user.uid)" type="warn">封禁</button>
			<button v-else-if="user.uidStatus === 'banned'" @click="() => unbanUser(user.uid)">解封</button>
			<template v-else>
			  <button @click="() => banUser(user.uid)" type="warn">封禁</button>
			  <button @click="() => unbanUser(user.uid)">解封</button>
			</template>

          </view>
        </view>
        <view class="admin-pagination">
          <button @click="() => userQuery.page--" :disabled="userQuery.page===0">上一页</button>
          <text>第{{userQuery.page+1}}页</text>
          <button @click="() => userQuery.page++" :disabled="!hasMoreUser">下一页</button>
        </view>
        <view v-if="userDetail">
          <view class="admin-detail">
            <view><text class="label">UID:</text> <text class="value">{{ userDetail.uid }}</text></view>
            <view><text class="label">昵称:</text> <text class="value">{{ userDetail.nickname }}</text></view>
            <view><text class="label">手机号:</text> <text class="value">{{ userDetail.phone }}</text></view>
            <view><text class="label">邮箱:</text> <text class="value">{{ userDetail.email }}</text></view>
            <view><text class="label">状态:</text> <text class="value">{{ userDetail.uidStatus }}</text></view>
            <button @click="() => userDetail=null">关闭</button>
          </view>
        </view>
      </view>
    </view>
    <view v-if="tab==='config'">
      <view class="admin-section">
        <view>
          <input v-model="association" placeholder="association 标识" />
          <button @click="reloadWordCloud">重新加载词云配置</button>
          <button @click="reloadRating">重新加载评级配置</button>
        </view>
      </view>
    </view>
    <view v-if="tab==='database'">
      <view class="admin-section">
        <view class="database-management">
          <view class="database-card">
            <text class="card-title">🗄️ SQL历史记录和回滚管理</text>
            <text class="card-description">管理数据库备份、查看SQL历史记录、执行一键回滚操作</text>
            <button class="btn btn-primary" @click="goToSqlHistory">进入SQL历史管理</button>
          </view>
          
          <view class="database-stats">
            <view class="stat-item">
              <text class="stat-label">数据库状态</text>
              <text class="stat-value">正常运行</text>
            </view>
            <view class="stat-item">
              <text class="stat-label">备份数量</text>
              <text class="stat-value">自动备份</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useUserStore } from '../../store/user'
import BackButton from '@/components/BackButton.vue'

const tab = ref('task')
const userStore = useUserStore()

// ====================== 通用确认函数 ========================
async function confirmAction(title: string, content: string): Promise<boolean> {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm)
      }
    })
  })
}

// ====================== 任务管理 ========================
const tasks = ref([])
const taskQuery = ref({ page: 0, size: 10, publisherId: '', status: '', keyword: '' })
const hasMoreTask = ref(true)

function getTasks() {
  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/tasks?page=${taskQuery.value.page}&size=${taskQuery.value.size}&publisherId=${taskQuery.value.publisherId}&status=${taskQuery.value.status}&keyword=${taskQuery.value.keyword}`,
    method: 'GET',
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      if (res.statusCode === 403) return uni.showToast({ title: '需要管理员权限', icon: 'none' })
      console.log("任务接口返回内容：", res.data.content)
      tasks.value = res.data.content || []
      hasMoreTask.value = !res.data.last
    },
	fail: () => uni.showToast({ title: '任务列表加载失败', icon: 'none' })
  })
}

async function deleteTask(id: number) {
  const task = tasks.value.find(t => t.taskId === id)
  const confirmed = await confirmAction('确认删除', `确定要删除任务《${task?.title || id}》吗？`)
  if (!confirmed) return

  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/task/${id}`,
    method: 'DELETE',
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      if (res.statusCode === 403) return uni.showToast({ title: '需要管理员权限', icon: 'none' })
      uni.showToast({ title: res.data, icon: 'success' })
      getTasks()
    },
    fail: () => uni.showToast({ title: '删除失败，请检查网络', icon: 'none' })
  })
}

watch(() => taskQuery.value.page, getTasks)


// ====================== 用户管理 ========================
const users = ref([])
const userQuery = ref({ page: 0, size: 10, keyword: '' })
const hasMoreUser = ref(true)
const userDetail = ref(null)

function getUsers() {
  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/users?page=${userQuery.value.page}&size=${userQuery.value.size}&keyword=${userQuery.value.keyword}`,
    method: 'GET',
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      if (res.statusCode === 403) return uni.showToast({ title: '需要管理员权限', icon: 'none' })
      users.value = res.data.content || []
      hasMoreUser.value = !res.data.last
    },
	fail: () => uni.showToast({ title: '用户列表加载失败', icon: 'none' })
  })
}

function showUserDetail(uid: number) {
  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/user/${uid}`,
    method: 'GET',
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      if (res.statusCode === 403) return uni.showToast({ title: '需要管理员权限', icon: 'none' })
      userDetail.value = res.data
    },
	fail: () => uni.showToast({ title: '用户信息获取失败', icon: 'none' })
  })
}

async function banUser(uid: number) {
  const user = users.value.find(u => u.uid === uid)
  const confirmed = await confirmAction('确认封禁', `确定要封禁用户「${user?.nickname || uid}」吗？`)
  if (!confirmed) return

  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/user/ban`,
    method: 'POST',
    data: { uid },
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      const updated = res.data
      const user = users.value.find(u => u.uid === uid)
      if (user) user.uidStatus = updated.uidStatus
      if (userDetail.value && userDetail.value.uid === uid) {
        userDetail.value.uidStatus = updated.uidStatus
      }
      uni.showToast({ title: '已封禁', icon: 'success' })
    },
    fail: () => uni.showToast({ title: '封禁失败，请检查网络', icon: 'none' })
  })
}

async function unbanUser(uid: number) {
  const user = users.value.find(u => u.uid === uid)
  const confirmed = await confirmAction('确认解封', `确定要解封用户「${user?.nickname || uid}」吗？`)
  if (!confirmed) return

  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/user/unban`,
    method: 'POST',
    data: { uid },
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      const updated = res.data
      const user = users.value.find(u => u.uid === uid)
      if (user) user.uidStatus = updated.uidStatus
      if (userDetail.value && userDetail.value.uid === uid) {
        userDetail.value.uidStatus = updated.uidStatus
      }
      uni.showToast({ title: '已解封', icon: 'success' })
    },
    fail: () => uni.showToast({ title: '解封失败，请检查网络', icon: 'none' })
  })
}

watch(() => userQuery.value.page, getUsers)


// ====================== 配置热加载 ========================

const association = ref('')
function reloadWordCloud() {
  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/wordCloud/reload?association=${association.value}`,
    method: 'GET',
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      if (res.statusCode === 403) return uni.showToast({ title: '需要管理员权限', icon: 'none' })
      uni.showToast({ title: res.data, icon: 'success' })
    },
    fail: () => uni.showToast({ title: '词云配置加载失败', icon: 'none' })
  })
}

function reloadRating() {
  uni.request({
    url: `${NETWORK_CONFIG.API_BASE_URL}/admin/rating/reload?association=${association.value}`,
    method: 'GET',
    header: { 'Access-Token': 'Bearer ' + userStore.token },
    success: (res) => {
      if (res.statusCode === 403) return uni.showToast({ title: '需要管理员权限', icon: 'none' })
      uni.showToast({ title: res.data, icon: 'success' })
    },
    fail: () => uni.showToast({ title: '评级配置加载失败', icon: 'none' })
  })
}

// ====================== 数据库管理 ========================
function goToSqlHistory() {
  uni.navigateTo({
    url: '/pages/admin/sql-history'
  })
}


// ====================== 页面初始化行为 ========================
onMounted(() => {
  if (tab.value === 'task') {
    getTasks()
  } else if (tab.value === 'user') {
    getUsers()
  }
})

watch(tab, (newTab) => {
  if (newTab === 'task') {
    getTasks()
  } else if (newTab === 'user') {
    getUsers()
  }
})
</script>


<style scoped>
/* 请保留基础布局、颜色、边距等兼容样式，删除所有 WXSS 不兼容语法 */
.admin-container { padding: 20rpx; }
.admin-tabs { display: flex; gap: 20rpx; margin-bottom: 20rpx; }
.admin-tabs button.active { font-weight: bold; color: #007aff; }
.admin-section { margin-bottom: 30rpx; }
.admin-search { display: flex; gap: 10rpx; margin-bottom: 10rpx; }
.admin-list-item { display: flex; align-items: center; gap: 10rpx; margin-bottom: 8rpx; }
.admin-pagination { margin-top: 10rpx; }
.admin-detail { background: #f5f5f5; padding: 10rpx; border-radius: 8rpx; margin-top: 10rpx; }
.label {
  font-weight: bold;
  margin-right: 10rpx;
}
.value {
  word-break: break-all;
  white-space: normal;
}
.admin-detail view {
  margin-bottom: 8rpx;
}

/* 数据库管理样式 */
.database-management {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.database-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40rpx;
  border-radius: 20rpx;
  text-align: center;
}

.card-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 20rpx;
}

.card-description {
  font-size: 28rpx;
  opacity: 0.9;
  display: block;
  margin-bottom: 30rpx;
}

.database-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.stat-item {
  background: white;
  padding: 30rpx;
  border-radius: 16rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.stat-label {
  color: #666;
  font-size: 24rpx;
  display: block;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
}

.btn {
  padding: 24rpx 48rpx;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary {
  background: white;
  color: #667eea;
  border: 2rpx solid white;
}

.btn-primary:hover {
  background: rgba(255,255,255,0.2);
  color: white;
}

</style> 